import { createPinia, defineStore } from 'pinia';

const pinia = createPinia();

const useGoodsStore = defineStore('goods', {
    state: () => ({
        // 确保 goodsList 被初始化为一个数组
        goodsList: [] 
    }),
    getters: {
        totalGoods(state) {
            // 添加空值检查
            return state.goodsList ? state.goodsList.length : 0; 
        },
        // 其他 getters 方法也可以添加类似的空值检查
        totalPrice(state) {
            return state.goodsList ? state.goodsList.reduce((total, good) => total + good.price * good.count, 0) : 0;
        },
        fullInfo(state) {
            return state.goodsList ? state.goodsList.map(good => `ID: ${good.id}, 名称: ${good.name}, 价格: ${good.price}, 数量: ${good.count}`) : [];
        }
    },
    actions: {
        addGood(good) {
            this.goodsList.push(good);
        }
    }
});

export { pinia, useGoodsStore };